package com.enjoylearning.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.enjoylearning.auth.service.AuthService;
import com.enjoylearning.ucenter.feignclient.CheckCodeClient;
import com.enjoylearning.ucenter.mapper.XcUserMapper;
import com.enjoylearning.ucenter.model.dto.AuthParamsDto;
import com.enjoylearning.ucenter.model.dto.XcUserExt;
import com.enjoylearning.ucenter.model.po.XcUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("password_authService")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private XcUserMapper xcUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CheckCodeClient checkCodeClient;

    //密码认证
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //账号
        String username = authParamsDto.getUsername();
        //校验验证码
        if (authParamsDto.getCheckcode() == null || authParamsDto.getCheckcode().trim().isEmpty()) {
            throw new RuntimeException("请输入验证码");
        }
        Boolean verify = checkCodeClient.verify(authParamsDto.getCheckcodekey(), authParamsDto.getCheckcode());
        if (!verify) {
            throw new RuntimeException("验证码错误");
        }
        //查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser == null) {
            throw new RuntimeException("账号不存在");
        }

        //正确密码
        String password = xcUser.getPassword();
        //用户输入的密码
        String userInputPassword = authParamsDto.getPassword();
        //校验
        boolean matches = passwordEncoder.matches(userInputPassword, password);
        if (!matches) {
            throw new RuntimeException("账号或密码错误");
        }

        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;
    }
}
